package cc.owoo.godpen.network.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by nimensei
 * 2022-03-01 上午 01:58
 **/
public abstract class HttpServer {
    /**
     * 启动服务器
     *
     * @param port 监听的端口号
     * @throws IOException 启动异常
     */
    public void launch(int port) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        while (true) {
            Socket socket = serverSocket.accept();
            if (socket == null)
                break;
            new Thread(() -> {
                try {
                    dispose(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    /**
     * 处理连接
     *
     * @param socket 连接对象
     * @throws IOException 处理异常
     */
    private void dispose(Socket socket) throws IOException {
        InputStream input = socket.getInputStream();
        OutputStream output = socket.getOutputStream();
        Request request = new Request();
        request.read(input);
        Response response = new Response();
        dispose(request, response);
        response.write(output);
        socket.close();
    }

    /**
     * 处理请求与响应
     *
     * @param request  请求对象
     * @param response 响应对象
     */
    public abstract void dispose(Request request, Response response);
}
